package com.foreknow.elmboot.service.impl;

import com.foreknow.elmboot.mapper.CartMapper;
import com.foreknow.elmboot.mapper.OrderDetailetMapper;
import com.foreknow.elmboot.mapper.OrdersMapper;
import com.foreknow.elmboot.po.Cart;
import com.foreknow.elmboot.po.OrderDetailet;
import com.foreknow.elmboot.po.Orders;
import com.foreknow.elmboot.service.OrdersService;
import com.foreknow.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderDetailetMapper orderDetailetMapper;

    @Override
    @Transactional
//流程执行完毕整
    public int creatOrders(Orders orders) {
        //1.查询当前的购物车中商家的所有食品
        Cart cart = new Cart();
        cart.setUserId(orders.getUserId());
        cart.setBusinessId(orders.getBusinessId());
        List<Cart> cartList = cartMapper.listCart(cart);
        //2.创建订单（返回一个订单编号）
        orders.setOrderDate(CommonUtil.getCurrentDate());
        //向orders中添加数据
        ordersMapper.saveOrders(orders);
        int orderId = orders.getOrderId();
        //3.创建一个订单的集合保存订单明细
            //对Cart进行遍历
        List<OrderDetailet> list = new ArrayList<>();
        for (Cart c : cartList) {
            OrderDetailet od = new OrderDetailet();
            //和订单表的orderid 关联
            od.setOrderId(orderId);
            od.setFoodId(c.getFoodId());
            od.setQuantity(c.getQuantity());
            //将明细添加到集合中
            list.add(od);
        }
        orderDetailetMapper.saveOrderDetailetBatch(list);
        //4.从购物车表中删除相关的食品信息
        cartMapper.deleteCart(cart);
        //将订单的id传递给前台
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        return ordersMapper.getOrdersById(orderId);
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        return ordersMapper.listOrdersByUserId(userId);
    }
}
